# -*- coding: utf-8 -*-
import sys

import oss2
from itertools import islice
import os
import logging
import time
import random
import io
from PIL import Image
from config.common import OSS_END_POINT, OSS_ACCESS_KEY, OSS_SECRET_KEY, OSS_BUCKET_NAME, OSS_REGION, OSS_BASE_PATH
from utils.date_utils import get_current_date_str

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

auth = oss2.AuthV4(OSS_ACCESS_KEY, OSS_SECRET_KEY)
bucket = oss2.Bucket(auth, OSS_END_POINT, OSS_BUCKET_NAME, region=OSS_REGION)


def create_bucket():
    try:
        bucket.create_bucket(oss2.models.BUCKET_ACL_PRIVATE)
        logging.info("Bucket created successfully")
    except oss2.exceptions.OssError as e:
        logging.error(f"Failed to create bucket: {e}")


def upload_file(object_name, data):
    try:
        result = bucket.put_object(object_name, data)
        logging.info(f"File uploaded successfully, status code: {result.status}")
        if result.status == 200:
            return object_name
    except oss2.exceptions.OssError as e:
        logging.error(f"Failed to upload file: {e}")


def download_file(object_name):
    try:
        file_obj = bucket.get_object(object_name)
        content = file_obj.read().decode('utf-8')
        logging.info("File content:")
        logging.info(content)
        return content
    except oss2.exceptions.OssError as e:
        logging.error(f"Failed to download file: {e}")


def list_objects():
    try:
        objects = list(islice(oss2.ObjectIterator(bucket), 500))
        for obj in objects:
            logging.info(obj.key)
    except oss2.exceptions.OssError as e:
        logging.error(f"Failed to list objects: {e}")


def delete_objects():
    try:
        objects = list(islice(oss2.ObjectIterator(bucket), 100))
        if objects:
            for obj in objects:
                bucket.delete_object(obj.key)
                logging.info(f"Deleted object: {obj.key}")
        else:
            logging.info("No objects to delete")
    except oss2.exceptions.OssError as e:
        logging.error(f"Failed to delete objects: {e}")


def delete_bucket():
    try:
        bucket.delete_bucket()
        logging.info("Bucket deleted successfully")
    except oss2.exceptions.OssError as e:
        logging.error(f"Failed to delete bucket: {e}")


def get_upload_path(object_name):
    return OSS_BASE_PATH + get_current_date_str() + "/" + object_name;


# 主流程
if __name__ == '__main__':
    # 1. 创建Bucket
    # create_bucket(bucket)
    # 2. 上传文件
    # PIL图像对象
    image = Image.open(
        'E:/work/hispatial/shaoxing/projects/docs-processing-server/temp/变压器检查记录表-2023-01-06-1-1.png')
    # 将PIL图像对象保存到字节流
    buffered = io.BytesIO()
    image.save(buffered, format='PNG')  # 确保使用正确的格式
    # 重置buffer指针到开始位置
    buffered.seek(0)
    upload_file(get_upload_path('变压器检查记录表-2023-01-06-222.png'), buffered)
    # 3. 下载文件
    # download_file(bucket, 'test-string-file')
    # 4. 列出Bucket中的对象
    list_objects()
    # 5. 删除Bucket中的对象
    # delete_objects(bucket)
    # 6. 删除Bucket
    # delete_bucket(bucket)
